package com.kaiwu.tc.persistence.builder.xml;

import com.kaiwu.tc.persistence.mapping.MappedStatement;
import com.kaiwu.tc.persistence.mapping.SqlCommandType;
import com.kaiwu.tc.persistence.session.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @author Captain
 * @date 2021/1/23
 **/
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration){
        this.configuration = configuration;
    }

    public void parse(InputStream in) throws DocumentException, ClassNotFoundException {
        Document document = new SAXReader().read(in);
        Element rootElement = document.getRootElement();
        for (SqlCommandType sqlCommandType : SqlCommandType.values()){
            List<Element> elements = rootElement.selectNodes("//"+sqlCommandType.name().toLowerCase());
            String namespace = rootElement.attributeValue("namespace");
            for (Element element : elements) {
                String id = element.attributeValue("id");
                String resultType = element.attributeValue("resultType");
                String parameterType = element.attributeValue("parameterType");
                MappedStatement mappedStatement = new MappedStatement();
                mappedStatement.setId(id);
                mappedStatement.setResultType(getClassType(resultType));
                mappedStatement.setParameterType(getClassType(parameterType));
                mappedStatement.setSql(element.getTextTrim());
                mappedStatement.setSqlCommandType(sqlCommandType);
                configuration.getStatementMap().put(namespace+"."+id, mappedStatement);
            }
        }
    }

    private Class<?> getClassType (String paramterType) throws
            ClassNotFoundException {
        if (paramterType == null){
            return null;
        }
        Class<?> aClass = Class.forName(paramterType);
        return aClass;
    }
}
